package main

import (
	item "cloudWego/kitex_gen/example/shop/item"
	"cloudWego/kitex_gen/example/shop/stock"
	"cloudWego/kitex_gen/example/shop/stock/stockservice"
	"context"
	"github.com/cloudwego/kitex/client"
	"github.com/kitex-contrib/registry-nacos/v2/resolver"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"log"
)

// ItemServiceImpl implements the last service interface defined in the IDL.
type ItemServiceImpl struct {
	stockCli stockservice.Client
}

func NewStockClient() (stockservice.Client, error) {
	sc := []constant.ServerConfig{
		*constant.NewServerConfig("192.168.8.140", 8848),
	}
	cc := constant.ClientConfig{
		NamespaceId:         "go-zero1",
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/nacos/log",
		CacheDir:            "tmp/nacos/cache",
		LogLevel:            "info",
		Username:            "nacos",
		Password:            "nacos",
	}

	cli, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
	if err != nil {
		panic(err)
	}

	//return stockservice.NewClient("example.shop.stock", client.WithHostPorts(addr))
	client, err := stockservice.NewClient("stock", client.WithResolver(resolver.NewNacosResolver(cli)))
	if err != nil {
		panic(err)
	}
	return client, nil
}

// GetItem implements the ItemServiceImpl interface.
func (s *ItemServiceImpl) GetItem(ctx context.Context, req *item.GetItemReq) (resp *item.GetItemResp, err error) {

	// TODO: Your code here...
	resp = item.NewGetItemResp()
	resp.Item = item.NewItem()
	resp.Item.Id = req.GetId()
	resp.Item.Title = "Item"
	resp.Item.Description = "v2"

	stockReq := stock.NewGetItemStockReq()
	stockReq.ItemId = req.GetId()
	stockResp, err := s.stockCli.GetItemStock(context.Background(), stockReq)
	if err != nil {
		log.Println("xxxxxxxxxxxxxxxxxx::::::", err)
		stockResp.Stock = 0
	}
	resp.Item.Stock = stockResp.GetStock()
	return
}
